package jee.boot.module.mail.interceptor;

import freemarker.template.Configuration;
import freemarker.template.Template;
import jee.boot.common.standard.AccountHandler;
import jee.boot.common.utils.StringUtils;
import jee.boot.entity.mail.Mail;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.util.Date;

/**
 * 默认的短信发送前置处理
 *
 * @author zhilei.wang
 */
@Component
public class DefaultMailPreInterceptor implements MailInterceptor {
    private Log log = LogFactory.getLog(DefaultMailPreInterceptor.class);
    @Autowired
//    private Configuration configuration; //freemarker
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private AccountHandler accountHandler;

    @Override
    public void process(Mail mail) throws Exception {
        // 邮件发送前,对数据进行预处理
        mail.setSendUser(accountHandler.getPrincipal());
        mail.setSentDate(new Date());
        // 如果设置了邮件模板,就按着模板进行发送
        if (StringUtils.isNotBlank(mail.getTemplateName())) {
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            Template template = configuration.getTemplate(mail.getTemplateName());
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, mail.getData());
            mail.setText(text);
        }
    }

}
